package com.data.modules.smzh.service.impl;


import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.data.common.api.vo.Result;
import com.data.common.constant.MsgConstants;
import com.data.common.constant.WebsocketConst;
import com.data.common.constant.enums.EventEnum;
import com.data.common.util.JwtIOTAuthUtil;
import com.data.common.util.KamliClientUtil;
import com.data.modules.message.websocket.WebSocket;
import com.data.modules.sm.entity.SmRepairStats;
import com.data.modules.sm.service.ISmRepairStatsService;
import com.data.modules.smzh.entity.*;
import com.data.modules.smzh.mapper.FacedeviceMapper;
import com.data.modules.smzh.mapper.SmDeviceLogsMapper;
import com.data.modules.smzh.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 设备日志表
 * @Author: data-boot
 * @Date:   2023-01-05
 * @Version: V1.0
 */
@Service
public class SmDeviceLogsServiceImpl extends ServiceImpl<SmDeviceLogsMapper, SmDeviceLogs> implements ISmDeviceLogsService {

    //报警类型
    private final static String stringWarnType = "1,3,7,9,11,13,15,17,19,201,202,203,204,205,206,207,208,210,211,213,301,302,303,304,220,3101";
    // 报修类型
    private final static String stringRepairType = "260,261,262,263,264,265";

    //开门方式
    private final static String stringOpenDoorType = "101,102,103,104";

    //开门方式
    private final static String stringOtherOpenDoorType = "100,107";

    //物业大屏监控信息
    private final static String stringAcconOpenDoorType = "101,102";

    @Autowired
    private IFacedeviceService facedeviceService;

    @Autowired
    private IDevicebuildService devicebuildService;

    @Autowired
    private FacedeviceMapper facedeviceMapper;

    @Autowired
    private SmDeviceLogsMapper smDeviceLogsMapper;

    @Autowired
    private ISmPersonTaskService taskService;

    @Autowired
    private IBuildinguserService userService;

    @Resource
    private WebSocket webSocket;

    @Autowired
    private ISmRepairStatsService smRepairStatsService;

    @Autowired
    private ISmAccMonitService smAccMonitService;

    @Autowired
    private IBuildinguserService buildinguserService;

    @Autowired
    private IUserCardService userCardService;



    @Override
    public void sendWarnMsg(SmDeviceLogs smDeviceLogs,String userId) {

        String userNo = "";

        if(ObjectUtil.equals(1,smDeviceLogs.getDeviceType())){//门口机

            Facedevice facedevice = facedeviceService.lambdaQuery().eq(Facedevice::getSerialNo,smDeviceLogs.getDeviceId()).one();
            if(ObjectUtil.isEmpty(smDeviceLogs.getNote())){
                smDeviceLogs.setNote(facedevice.getAddress());
            }

            //通过门口机序列号查找绑定的单元号
            Devicebuild devicebuild = devicebuildService.lambdaQuery().eq(Devicebuild::getSerialNo,smDeviceLogs.getDeviceId()).one();

            userNo = devicebuild.getBuildingNo().substring(0,10);
        }else{// 智慧屏
            //组装数据发送消息到 管理机
            userNo = smDeviceLogs.getDeviceId().substring(0,10);

            try {
                String buildNo = smDeviceLogs.getDeviceId();
                SmUser user = userService.queryUserInfoByBuildNo(smDeviceLogs.getDeviceId());
                SmPersonTask task = new SmPersonTask();
                if(ObjectUtil.equals(209,smDeviceLogs.getEventCode())){//紧急报警

                    task.setCreateBy(userId).setLevel(1).setLogId(smDeviceLogs.getId())
                            .setStatus(1)
                            .setMobile(user.getPersonCode())
                            //.setRoomNo(smDeviceLogs.getDeviceId())
                           .setRoomNo(buildNo.substring(10,13).concat("栋").concat(buildNo.substring(13,15)
                                   .concat("单元").concat(buildNo.substring(15,19)).concat("房间")))
                            //.setRoomNo(buildNo.substring(10,13).concat("栋"))
                            .setName(user.getPersonName());
                    taskService.save(task);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //通过序列号查询
        List<Facedevice> facedeviceList = facedeviceService.lambdaQuery().likeRight(Facedevice::getSerialNo,userNo).list();
        facedeviceList.stream().forEach(x->{
            String cmdCode = MsgConstants.ALARM_MSG;
            List list = new ArrayList<>();
            list.add(smDeviceLogs);

            KamliClientUtil.doPostpushMsgUr(x.getSerialNo(),cmdCode,list);
        });

    }

    @Override
    public void synPersonTodo(SmDeviceLogs smDeviceLogs, String userId) {
        String userNo = "";

        if(ObjectUtil.equals(1,smDeviceLogs.getDeviceType())){//门口机

            Facedevice facedevice = facedeviceService.lambdaQuery().eq(Facedevice::getSerialNo,smDeviceLogs.getDeviceId()).one();
            if(ObjectUtil.isEmpty(smDeviceLogs.getNote())){
                smDeviceLogs.setNote(facedevice.getAddress());
            }

            //通过门口机序列号查找绑定的单元号
            Devicebuild devicebuild = devicebuildService.lambdaQuery().eq(Devicebuild::getSerialNo,smDeviceLogs.getDeviceId()).one();

            userNo = devicebuild.getBuildingNo().substring(0,10);
        }else{// 智慧屏
            //组装数据发送消息到 管理机
            userNo = smDeviceLogs.getDeviceId().substring(0,10);

            try {
                String buildNo = smDeviceLogs.getDeviceId();
                SmUser user = userService.queryUserInfoByBuildNo(smDeviceLogs.getDeviceId());
                SmPersonTask task = new SmPersonTask();

                task.setCreateBy(userId).setLevel(2).setLogId(smDeviceLogs.getId())
                        .setStatus(1)
                        .setMobile(user.getPersonCode())
                        //.setRoomNo(smDeviceLogs.getDeviceId())
                        .setRoomNo(buildNo.substring(10,13).concat("栋").concat(buildNo.substring(13,15)
                                .concat("单元").concat(buildNo.substring(15,19)).concat("房间")))
                        //.setRoomNo(buildNo.substring(10,13).concat("栋"))
                        .setName(user.getPersonName());
                taskService.save(task);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public Result<?> searchAlarmInfo(SmDeviceLogs smDeviceLogs, HttpServletRequest req) {
        String appId = JwtIOTAuthUtil.getTokenByRequest(req);
        if(ObjectUtil.isEmpty(appId)){
            return Result.error(10001,"无效token");
        }else{

            List<SmDeviceLogs> list = smDeviceLogsMapper.searchAlarmList(smDeviceLogs);

            return Result.ok(0,list);
        }

    }

    @Override
    public Result<?> searchRepairInfo(SmDeviceLogs smDeviceLogs, HttpServletRequest req) {
        String appId = JwtIOTAuthUtil.getTokenByRequest(req);
        if(ObjectUtil.isEmpty(appId)){
            return Result.error(10001,"无效token");
        }else{

            List<SmDeviceLogs> list = smDeviceLogsMapper.searchRepairInfo(smDeviceLogs);

            return Result.ok(0,list);
        }
    }

    @Override
    public void saveInfo(SmDeviceLogs smDeviceLogs,String userId) {

        this.save(smDeviceLogs);

        JSONObject obj = new JSONObject();
        //通过设备类型 获取到相关用户信息

        //报警消息  发送到物业大屏
        if(ObjectUtil.equals(1,smDeviceLogs.getLogType())){//1:报警
            if(stringWarnType.contains(String.valueOf(smDeviceLogs.getEventCode()))){

                //obj.put(WebsocketConst.MSG_TYPE,"3");//报警
               // webSocket.sendMessage(userId, obj.toJSONString());

                sendMsgSocket(userId, EventEnum.TYPE_ALARM.getCode(),smDeviceLogs);
                //所有的报警都同步到管理机
                this.sendWarnMsg(smDeviceLogs,userId);
            }
            if(ObjectUtil.equals(209,smDeviceLogs.getEventCode())){//紧急报警
                this.sendWarnMsg(smDeviceLogs,userId);

              /*  obj.put(WebsocketConst.MSG_TYPE,"1");//紧急报警
                webSocket.sendMessage(userId, obj.toJSONString());*/

                sendMsgSocket(userId,EventEnum.TYPE_EMERG.getCode(),smDeviceLogs);
            }
        }

        if(stringRepairType.contains(String.valueOf(smDeviceLogs.getEventCode()))){

            if(ObjectUtil.equals(265,smDeviceLogs.getEventCode())){
                //智慧屏服务
                this.synPersonTodo(smDeviceLogs,userId);
            }

          /*  obj.put(WebsocketConst.MSG_TYPE,"2");//报修
            webSocket.sendMessage(userId,obj.toJSONString());*/

            sendMsgSocket(userId,EventEnum.TYPE_SERVE.getCode(),smDeviceLogs);//报修

            SmRepairStats smRepairStats = new SmRepairStats();
            smRepairStats.setDeviceNo(smDeviceLogs.getDeviceId());
            smRepairStats.setType(smDeviceLogs.getEventCode());
            smRepairStats.setCreateBy(userId);
            smRepairStatsService.save(smRepairStats);
        }


        if(stringOtherOpenDoorType.contains(String.valueOf(smDeviceLogs.getEventCode()))
                && ObjectUtil.equals(401,smDeviceLogs.getResult())){
            SmAccMonit smAccMonit = new SmAccMonit();
            smAccMonit.setType(2);
            smAccMonit.setBuidNo(smDeviceLogs.getSipNo());
            smAccMonit.setCreateBy(userId);
            obj.put(WebsocketConst.MSG_TYPE,"4");//人员监控
           // webSocket.sendMessage( userId,obj.toJSONString());

            smAccMonitService.save(smAccMonit);
        }
        if(stringAcconOpenDoorType.contains(String.valueOf(smDeviceLogs.getEventCode()))
                && ObjectUtil.equals(401,smDeviceLogs.getResult())){

            String buildNo = "";
            if(ObjectUtil.equals(101,smDeviceLogs.getEventCode())){//人脸开门 通过人员id
                Buildinguser buildinguser = buildinguserService.lambdaQuery().eq(Buildinguser::getUserId,smDeviceLogs.getNote()).last("limit 1").one();
                buildNo = buildinguser.getUniqueNo();
            }else{//刷卡开门
                UserCard userCard = userCardService.lambdaQuery().eq(UserCard::getCardNumber,smDeviceLogs.getCardId()).last("limit 1").one();
                Buildinguser buildinguser = buildinguserService.lambdaQuery().eq(Buildinguser::getUserId,userCard.getUserId()).last("limit 1").one();
                buildNo = buildinguser.getUniqueNo();
            }
            SmAccMonit smAccMonit = new SmAccMonit();
            smAccMonit.setType(1);
            smAccMonit.setCreateBy(userId);
            smAccMonit.setBuidNo(buildNo);
            obj.put(WebsocketConst.MSG_TYPE,"4");//人员监控
            //webSocket.sendMessage(userId,obj.toJSONString());

            smAccMonitService.save(smAccMonit);
        }

    }

    @Override
    public void sendMessage(SmDeviceLogs smDeviceLogs, String userId,String type) {

        sendMsgSocket(userId,type,smDeviceLogs);
    }

    /**
     * type 1:紧急报警 2：其他报警 3：报修 4：人员进出
     * @param userId
     * @param type
     */
    private void sendMsgSocket(String userId,String type,SmDeviceLogs smDeviceLogs){

        JSONObject obj = new JSONObject();
        obj.put(WebsocketConst.MSG_TXT, userParams(smDeviceLogs));
        obj.put(WebsocketConst.MSG_TYPE,type);//人员监控
        webSocket.sendMessage(userId,obj.toJSONString());
    }

    private String userParams(SmDeviceLogs smDeviceLogs){

        if(ObjectUtil.equals(1,smDeviceLogs.getDeviceType())){//门口机
            return "门口机:"+smDeviceLogs.getEventName();
        }else if(ObjectUtil.equals(2,smDeviceLogs.getDeviceType())){//室内机
            return smDeviceLogs.getDeviceId().substring(10,13).concat("栋").concat(smDeviceLogs.getDeviceId().substring(13,15)
                    .concat("单元").concat(smDeviceLogs.getDeviceId().substring(15,19))).concat("房间").concat(":").concat(smDeviceLogs.getEventName());
        }else if(ObjectUtil.equals(3,smDeviceLogs.getDeviceType())){//养老手环
            return "养老手环设备编号："+smDeviceLogs.getDeviceId().concat("，位置：").concat(smDeviceLogs.getEventName());
        }else if(ObjectUtil.equals(4,smDeviceLogs.getDeviceType())){//摔倒检测
            return "摔倒检测设备编号："+smDeviceLogs.getDeviceId().concat("，").concat(smDeviceLogs.getEventName());
        }else{
            return "";
        }
    }

}
